package cn.edu.fzu.delivery.filter.impl;

import cn.edu.fzu.delivery.domain.entity.CourierDelivery;
import cn.edu.fzu.delivery.domain.entity.SysUser;
import cn.edu.fzu.delivery.filter.DeliveryFilter;
import cn.edu.fzu.delivery.filter.DeliveryFilterDto;
import cn.edu.fzu.delivery.handler.DeliverySession;
import cn.edu.fzu.delivery.service.CourierDeliveryService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 过滤掉已经派送该快递的快递员。理论上一个快递员之后派送一次同一个快递，但是系统中存在揽件快递员，和派送快递员，可能揽件和派送的是同一个
 * 
 * @author fangxin
 * @date 2022/11/18
 */
@Component("deliveredFilter")
public class DeliveredFilter implements DeliveryFilter {

    @Resource
    private CourierDeliveryService courierDeliveryService;

    @Override
    public boolean prepare(DeliverySession session, DeliveryFilterDto dto) {
        List<SysUser> sysUsers = session.getDeliveryManPool();
        if (CollectionUtils.isEmpty(sysUsers)) {
            return false;
        }
        String courierId = session.getCourier().getCourierId();
        Map<Long, Boolean> map = Maps.newHashMapWithExpectedSize(sysUsers.size());
        for (SysUser user : sysUsers) {
            CourierDelivery delivery = courierDeliveryService.getByCourierIdAndDeliveryManId(courierId, user.getId());
            map.put(user.getId(), delivery != null);
        }
        dto.setDeliveredMap(ImmutableMap.copyOf(map));
        return true;
    }


    @Override
    public boolean filter(SysUser user, DeliveryFilterDto dto) {
        return dto.getDeliveredMap().get(user.getId());
    }
}
